﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SquareRootOfANumber
{
    /// <summary>
    /// Extension Method to calculate the SquareRoot of a positive real number
    /// </summary>
    internal static class DoubleExtension
    {
        /// <summary>
        /// Get the SquareRoot of a given number using Babylonian method: 
        ///     Rx+1 = (Rx + (N/Rx))/2
        ///         where
        ///             N = Number that want to get the square root
        ///             Rx = Initial Guess
        /// </summary>
        /// <param name="number">Number to be square rooted</param>
        /// <returns>The square root of the given number</returns>
        internal static double SquareRoot(this double number)
        {
            if (number <= 0)
                return 0;

            //Store the value for Rx+1
            double current = GetInitialGuess(number);
            //Store the Rx values
            double previous = 0;

            //While Rx and Rx+1 be differents
            while (current != previous)
            {
                // Rx    =  Rx+1
                previous = current;
                // Rx+1 = (   Rx    +   N    /    Rx   ) / 2
                current = (previous + number / previous) / 2;
            }

            return current;
        }

        /// <summary>
        /// Get an initial guess obtaining the closest quadratic number to the given number
        /// </summary>
        /// <param name="number">Number to be square rooted</param>
        /// <returns>The closest number (to the square) to the given number </returns>
        private static int GetInitialGuess(double number)
        {
            int i = 0;
            while (i * i < number)
                i++;

            return i - 1;
        }
    }
}
